package com.ajie.service.impl;

import com.ajie.config.security.service.UserDetailServiceImpl;
import com.ajie.entity.LookLikeFavourite;
import com.ajie.entity.SysUser;
import com.ajie.mapper.SysUserMapper;
import com.ajie.service.SysUserService;
import com.ajie.utils.*;
import com.ajie.vo.LoginVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.*;

@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private UserDetailServiceImpl detailServiceImpl;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private TokenUtil tokenUtil;


    @Value("${jwt.tokenHead}")
    private  String tokenHead;
    
    @Autowired
    private RedisUtil redisUtil;



    @Override
    public Result login(LoginVo loginVo) {
        log.info("该文件名是：SysUserServiceImpl,该方法是：login");
        UserDetails userDetails;
        if (loginVo.getType() == 2){
            if (!StringUtil.isNotEmpty(loginVo.getPhoneNumber()) ||  !StringUtil.isNotEmpty(loginVo.getCode())){
                return Result.fail("请填写完整手机号或验证码信息！");
            }
            //验证码对比
            Object  code = redisUtil.getValue(loginVo.getPhoneNumber() + "sms");
            if ( code == null) {
                return Result.fail("验证码已过期！");
            }
            code = code.toString();
            System.out.println(code);
            if (!code.equals(loginVo.getCode())){
                return Result.fail("验证码不正确！");
            }
            userDetails = detailServiceImpl.loadUserByUsername(loginVo.getPhoneNumber());
        }else {
            if (!StringUtil.isNotEmpty(loginVo.getUsername()) ||  !StringUtil.isNotEmpty(loginVo.getPassword())){
                return Result.fail("请填写正确的的账户或密码！");
            }
            log.info("1.开始登录" + loginVo);
            userDetails = detailServiceImpl.loadUserByUsername(loginVo.getUsername());
    
            log.info("2.判断账号是否存在，密码是否正确"+ userDetails);
            if(null == userDetails || !passwordEncoder.matches(MD5Utils.md5(loginVo.getPassword()), userDetails.getPassword())){
                return Result.fail("账号或密码错误，请重新输入");
            }
        }
        if (!userDetails.isEnabled()){
            return Result.fail("该账号已禁用,请联系管理员！");
        }
        log.info("登录成功！在security对象中存入登陆者信息");
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        log.info("根据登录信息获取token");
        //需要借助jwt来生成token
        String token = tokenUtil.generateToken(userDetails);
        Map<String,String> map = new HashMap<>(2);
        map.put("tokenHead",tokenHead);
        map.put("token",token);
        return Result.success("登录成功！",map);
    }
    
    @Override
    public Result findByUserName(String username) {
        log.info("该文件名是：SysUserServiceImpl,该方法是：findByUserName");
        SysUser user = userMapper.findByUserName(username);
        return Result.success("查找用户成功",user);
    }
    
    @Transactional
    @Override
    public Result insert(SysUser user) {
        log.info("该文件名是：SysUserServiceImpl,该方法是：insert");
        //健壮性判断
        SysUser user1 = userMapper.findByUserName(user.getUsername());
        if (null != user1){
            return Result.fail("添加失败，该用户已存在");
        }
        user.setPassword(passwordEncoder.encode(MD5Utils.md5(user.getPassword())));
        System.out.println(user);
        userMapper.insert(user);
        log.info("添加对应的用户数据");
        if (user.getRoles() != null){
            user.getRoles().forEach(item ->{userMapper.insertRoles(user.getId(),item.getId());
                System.out.println("角色id是："+item.getId());
            });
        }
        return Result.success("添加用户数据成功");
    }
    @Transactional
    @Override
    public Result update(SysUser user) {
        log.info("该文件名是：SysUserServiceImpl,该方法是：update");
        if(userMapper.findRoles(user.getId()).size()>0){
            log.info("先删除对应的角色数据");
            userMapper.deleteRoles(user.getId());
        }
        log.info("再添加对应的角色数据");
        user.getRoles().forEach(item ->userMapper.insertRoles(user.getId(),item.getId()));
        userMapper.update(user);
        return Result.success("修改用户数据成功");
    }
    
    @Override
    public Result delete(Long id) {
        log.info("该文件名是：SysUserServiceImpl,该方法是：delete");
        log.info("查询该角色信息下是否有角色");
        if(userMapper.findRoles(id).size() > 0){
            userMapper.deleteRoles(id);
        }
        //删除角色信息
        userMapper.delete(id);
        return Result.success("删除用户数据成功");
    }
    
    @Override
    public Result findPage(QueryInfo queryInfo) {
        log.info("该文件名是：SysUserServiceImpl,该方法是：findPage");
        log.info("1.开始权限数据分页-->页码{}, -->页数{}, -->查询内容{}",queryInfo.getPageNumber(),queryInfo.getPageSize(),queryInfo.getQueryString());
        PageHelper.startPage(queryInfo.getPageNumber(),queryInfo.getPageSize());
        Page<SysUser> page = userMapper.findPage(queryInfo.getQueryString());
        long total = page.getTotal();
        List<SysUser> result = page.getResult();
        result.forEach(item ->{
            item.setRoles(userMapper.findRoles(item.getId()));
        });
        return PageResult.pageResult(total,result);
    }
    
    /**
     * 根据邮箱修改密码
     * @param mail
     * @param password
     */
    @Override
    public void updatePwdByMail(String mail, String password) {
        log.info("该文件名是：SysUserServiceImpl,该方法是：updatePwdByMail");
        log.info("邮箱修改密码");
        userMapper.updatePwdByMail(mail,password);
    }
    
    @Override
    public List<LookLikeFavourite> findLookLikeFavourite() {
        return userMapper.findLookLikeFavourite();
    }
    
    @Override
    public void updateLookLikeFavourite(LookLikeFavourite lookLikeFavourite) {
        userMapper.updateLookLikeFavourite(lookLikeFavourite);
    }
    
    @Override
    public List<LookLikeFavourite> findLookLikeFavouriteByReid(LookLikeFavourite lookLikeFavourite2) {
        return userMapper.findLookLikeFavouriteByReid(lookLikeFavourite2);
    }
    
    @Override
    public void delLookLikeFavourite() {
        userMapper.delLookLikeFavourite();
    }
    
    @Override
    public void insertLookLikeFavouriteByReid(LookLikeFavourite lookLikeFavourite1) {
        userMapper.insertLookLikeFavouriteByReid(lookLikeFavourite1);
    }
    
    @Override
    public Result findExpert(QueryInfo queryInfo) {
        log.info("该文件名是：SysUserServiceImpl,该方法是：findPage");
        log.info("1.开始权限数据分页-->页码{}, -->页数{}, -->查询内容{}",queryInfo.getPageNumber(),queryInfo.getPageSize(),queryInfo.getQueryString());
        PageHelper.startPage(queryInfo.getPageNumber(),queryInfo.getPageSize());
        Page<SysUser> page = userMapper.findExpert(queryInfo.getQueryString());
        long total = page.getTotal();
        List<SysUser> result = page.getResult();
        result.forEach(item ->{
            item.setRoles(userMapper.findRoles(item.getId()));
        });
        return PageResult.pageResult(total,result);
    }
    
    @Override
    public void reset() {
        userMapper.reset();
    }
    
    
}
